package internal

import (
	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

type Gormx struct{}

func DBNew() *Gormx {
	return &Gormx{}
}
func (m *Gormx) Gormx(c *Config) (DB *gorm.DB) {
	var err error
	// 设置日志级别
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
		},
	)
	// 打开数据库连接
	DB, err = gorm.Open(mysql.Open(c.Database.Link), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		log.Fatalf("failed to connect database: %v", err)
	}

	// 获取底层的数据库连接池
	sqlDB, err := DB.DB()
	if err != nil {
		log.Fatalf("failed to get sql.DB: %v", err)
	}

	// 测试数据库连接
	err = sqlDB.Ping()
	if err != nil {
		log.Fatalf("failed to ping database: %v", err)
	}
	// log.Println("Connected to the database successfully.")

	return DB
}

func initDb() {
	DB = DBNew().Gormx(C)
}
